<template>
  <div>
    <!-- 开票操作 -->
    <u-dialog :title="title" :show.sync="show" width="1040px" :auto-close="false" :footer="true" @cancel="cancel" @confirm="confirm">
      <el-form ref="dataForm" :model="dataForm">
        <el-descriptions size="medium" border :column="1" title="开票订单">
          <el-descriptions-item label="订单号">
            <el-row>
              <el-col :span="12">
                <el-form-item prop="orderNo" style="margin: 0 0;">
                  {{ dataForm.orderNo }}
                </el-form-item>
              </el-col>
            </el-row>
          </el-descriptions-item>
          <el-descriptions-item label="发票类型">
            <el-form-item prop="invoiceType" style="margin: 0 0;">
              <el-radio-group v-model="dataForm.invoiceType">
                <el-radio :label="1">数电普通发票</el-radio>
                <el-radio :label="2">数电专用发票</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="开票金额">
            <el-form-item prop="totalFee" style="margin: 0 0;">
              {{ dataForm.totalFee }}
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="商品明细">
            <el-form-item v-if="dataForm.order" style="margin: 0 0;">
              <el-table :data="dataForm.order.goodsList" :border="true">
                <el-table-column key="goods_name" label="商品名称" prop="goods_name">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.goods_name" size="small" />
                  </template>
                </el-table-column>
                <el-table-column key="specification" label="规格" prop="specification">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.specification" size="small" />
                  </template>
                </el-table-column>
                <el-table-column key="num" label="数量" prop="num">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.num" :min="1" placeholder="" />
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
        <el-descriptions v-if="dataForm.title" size="medium" border :column="2" title="开票信息" style="margin-top: 20px">
          <el-descriptions-item :span="12" label="抬头类型">
            <el-radio-group v-model="dataForm.title.type">
              <el-radio :label="1">个人/非企业单位</el-radio>
              <el-radio :label="2">企业</el-radio>
            </el-radio-group>
          </el-descriptions-item>

          <el-descriptions-item :span="12">
            <template slot="label">
              邮箱地址<span class="required" />
            </template>
            <el-form-item :prop="getPropName('email')" :rules="getRules('邮箱地址')" style="margin: 0 0;">
              <el-input v-model="dataForm.title.email" placeholder="邮箱地址" clearable />
            </el-form-item>
          </el-descriptions-item>

          <el-descriptions-item>
            <template slot="label">
              发票抬头<span class="required" />
            </template>
            <el-form-item :prop="getPropName('title')" :rules="getRules('发票抬头')" style="margin: 0 0;">
              <el-autocomplete
                v-model="dataForm.title.title"
                style="width: 100%;"
                :fetch-suggestions="querySearchAsync"
                placeholder="发票抬头"
                @select="handleSelect"
              />
            </el-form-item>
          </el-descriptions-item>

          <el-descriptions-item>
            <template slot="label">
              纳税识别号<span v-if="dataForm.title && dataForm.title.type === 2" class="required" />
            </template>
            <el-form-item :prop="getPropName('taxNo')" :rules="{ required: dataForm.title && dataForm.title.type === 2, message: '请填写纳税识别号', trigger: 'blur' }" style="margin: 0 0;">
              <el-input v-model="dataForm.title.taxNo" placeholder="纳税识别号" clearable />
            </el-form-item>
          </el-descriptions-item>

          <el-descriptions-item :span="12">
            <template slot="label">
              开票备注
            </template>
            <el-form-item prop="remark" style="margin: 0 0;">
              <el-input v-model="dataForm.remark" placeholder="开票备注（选填）" type="textarea" clearable rows="3" />
            </el-form-item>
          </el-descriptions-item>

          <!-- 右侧内容 -->
          <template v-if="dataForm.memberId" #extra>
            <el-button type="primary" icon="el-icon-search" @click="selectInvoiceTitle">发票抬头</el-button>
          </template>
        </el-descriptions>
      </el-form>
    </u-dialog>

    <el-drawer
      title="发票抬头"
      :visible.sync="drawerVisible"
      direction="rtl"
      size="70%"
    >
      <u-table
        :data="titleList"
        :columns="columns"
        :page="false"
      >
        <template v-slot:right>
          <el-table-column label="操作" align="center" fixed="right">
            <template slot-scope="{ row }">
              <el-button type="text" @click="chooseTitle(row)">选择</el-button>
            </template>
          </el-table-column>
        </template>
      </u-table>
    </el-drawer>
  </div>
</template>

<script>
/**
 * 业务组件 - 开票操作
 */
export default {
  name: 'AddOrderPoints',
  components: {
  },
  model: {
    prop: 'show',
    event: 'changeShow'
  },
  props: {
    /** 是否弹框 */
    show: {
      type: Boolean,
      default: false
    },
    /** 选中的数据 */
    data: {
      type: Object,
      default: data => {
        return ({
          card_id: '',
          member_name: ''
        })
      }
    }
  },
  data() {
    return {
      flag: false, // 是否可开票 打开窗口
      restaurants: [],
      timeout: null,
      api: this.$u.api.PluginsInvoicing,
      titleList: [],
      columns: [
        {
          prop: 'type',
          label: '抬头类型',
          formatter: (row) => {
            if (row.title.type === 1) {
              return '个人/非企业单位'
            } else {
              return '企业'
            }
          }
        },
        {
          prop: 'email',
          label: '邮箱地址'
        },
        {
          prop: 'title',
          label: '发票抬头'
        },
        {
          prop: 'taxNo',
          label: '纳税识别号'
        }
      ],
      drawerVisible: false,
      title: '订单开票查询',
      param: {},
      dataForm: {
      }
    }
  },
  watch: {
    show(newVal, oldVal) {
      // console.log(newVal + '---------------' + oldVal)
      // 监听是否弹框,决定是否初始化数据
      if (newVal) {
        const newForm = {
          invoiceType: 1
        }
        this.param = this.$u.deepMerge(newForm, this.data)
        this.dataForm = this.param
      }
    }
  },
  methods: {
    getPropName(field) {
      return `title.${field}`
    },
    getRules(field) {
      const required = this.dataForm.invoiceType === 2 && (this.dataForm.title && this.dataForm.title.type === 2)
      const rules = []
      if (required) {
        rules.push({ required: true, message: `请填写${field}`, trigger: 'blur' })
      }
      return rules
    },
    // 开票信息
    getInvoiceDetail(row) {
      const self = this
      const { sale_no, vipcard_no } = row
      const data = {
        'orderNo': sale_no,
        'card_no': vipcard_no
      }
      return this.api.info(data).then(res => {
        self.dataForm = res.data
        self.dataForm.orderNo = sale_no
        self.dataForm.invoiceType = parseInt(res.data.invoiceType)
        if (self.dataForm.title === null) {
          const title = {
            title: '',
            email: '',
            type: 1,
            taxNo: '',
            addr: '',
            mobile: '',
            bankName: '',
            bankNo: ''
          }
          self.$set(self.dataForm, 'title', title)
        }
        return res.code === 20000
      }).catch(() => {
        return false
      })
    },
    // 企业列表
    querySearchAsync(queryString, cb) {
      // 提前退出条件，减少不必要的执行
      if (queryString.length < 4 || this.dataForm.title.type !== 2) {
        return
      }

      const data = {
        'keyword': queryString
      }

      // 使用解构赋值简化代码
      this.api.enterpriseList(data).then(({ data: enterprises }) => {
        // 使用箭头函数简化map回调
        const list = enterprises.map(({ companyid, entname }) => ({ id: companyid, value: entname }))

        // 清除之前的定时器，防止内存泄漏
        clearTimeout(this.timeout)

        // 使用箭头函数简化setTimeout回调
        this.timeout = setTimeout(() => cb(list), 3000 * Math.random())
      })
    },
    // 处理选项选择的逻辑
    handleSelect(item) {
      this.api.enterpriseQuery({
        'companyId': item.id
      }).then(res => {
        this.dataForm.title.title = res.data.enterpriseName
        this.dataForm.title.taxNo = res.data.taxNumber
        this.dataForm.title.addr = res.data.operationLocation
      })
    },
    // 查询发票抬头列表
    selectInvoiceTitle() {
      const { memberId } = this.dataForm
      this.api.titleList({
        'card_no': memberId
      }).then(res => {
        // 通知信息
        this.titleList = res.data
        this.drawerVisible = true
      })
    },
    // 选择抬头
    chooseTitle(row) {
      this.dataForm.title = row
      this.drawerVisible = false
    },
    // 验证表单数据
    validate() {
      // 数电专用发票抬头类型需为企业
      if (this.dataForm.title.type === 1 && this.dataForm.invoiceType === 2) {
        this.$message.error('数电专用发票抬头类型需为企业！')
        return false
      }

      if (!this.$u.test.email(this.dataForm.title.email)) {
        this.$message.error('邮箱格式不正确')
        return false
      }

      if (this.$u.test.isEmpty(this.dataForm.title.title)) {
        this.$message.error('发票抬头必填')
        return false
      }

      // 验证商品信息
      const errorRows = this.dataForm.order.goodsList.filter(row => !row.goods_name || !row.num)
      if (errorRows.length > 0) {
        this.$message.error('请输入完整的商品信息')
        return false
      }

      return true
    },
    // 确认
    confirm() {
      // 验证表单
      if (!this.validate()) {
        return
      }

      const { memberId } = this.dataForm

      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          if (!this.$u.test.isEmpty(memberId)) {
            // 会员直接开票
            this.invoicing()
          } else {
            // 非会员
            this.save()
          }
        }
      })
    },
    invoicing() {
      this.$confirm('您确定开具发票,请谨慎操作', '提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        // 个人
        if (this.dataForm.title.type === 1) {
          this.dataForm.title.addr = ''
          this.dataForm.title.bankName = ''
          this.dataForm.title.bankNo = ''
          this.dataForm.title.mobile = ''
        }

        // 处理会员发票
        this.api.invoicing(this.dataForm).then(() => {
          // 通知信息
          this.$u.msg('开票成功')
          this.$emit('confirm')
        })
      }).catch(() => {
        // 可以在这里处理取消操作或者不需要额外处理的场景
      })
    },
    save() {
      this.$confirm('面对面开票,请顾客扫码确认开票信息！', '提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        // 个人
        if (this.dataForm.title.type === 1) {
          this.dataForm.title.addr = ''
          this.dataForm.title.bankName = ''
          this.dataForm.title.bankNo = ''
          this.dataForm.title.mobile = ''
        }

        // 处理会员发票
        this.api.save(this.dataForm).then(() => {
          // 通知信息
          this.$u.msg('保存成功')
          this.$emit('confirm')
        })
      }).catch(() => {
        // 可以在这里处理取消操作或者不需要额外处理的场景
      })
    },
    // 关闭或者取消
    cancel() {
      this.$emit('changeShow', false)
      this.$emit('cancel')
    }
  }
}
</script>
<style>
.required::before {
  content: "*";
  color: red;
}
</style>
